
import defaultSetting from './config.js';
import { common_extend, nameStyleConvert } from './utils/util';
import Store from './store';
import server from './controllers/server';
import luckysheetConfigsetting from './controllers/luckysheetConfigsetting';
import sheetmanage from './controllers/sheetmanage';
import luckysheetsizeauto from './controllers/resize';
import luckysheetHandler from './controllers/handler';
import { initialFilterHandler } from './controllers/filter';
import { initialMatrixOperation } from './controllers/matrixOperation';
import { initialSheetBar } from './controllers/sheetBar';
import { formulaBarInitial } from './controllers/formulaBar';
import { rowColumnOperationInitial } from './controllers/rowColumnOperation';
import { keyboardInitial } from './controllers/keyboard';
import { orderByInitial } from './controllers/orderBy';
import { initPlugins } from './controllers/expendPlugins';
import loadAttechment from './controllers/loadAttechment';
import hyperlinkCtrl from './controllers/hyperlinkCtrl';
import editor from './global/editor';

import {
    getluckysheetfile,
    getluckysheet_select_save,
    getconfig
} from './methods/get';
import { setCellValue } from './global/api';
import {
    setluckysheet_select_save
} from './methods/set';
import { luckysheetrefreshgrid, jfrefreshgrid } from './global/refresh';
import functionlist from './function/functionlist';
import { luckysheetlodingHTML } from './controllers/constant';
import { getcellvalue, getdatabyselection } from './global/getdata';
import { setcellvalue } from './global/setdata';
import { selectHightlightShow } from './controllers/select';
import { zoomInitial } from './controllers/zoom';
import { printInitial } from './controllers/print';
import method from './global/method';

import * as api from './global/api';

import flatpickr from 'flatpickr';
import Mandarin from 'flatpickr/dist/l10n/zh.js';
import { initListener } from './controllers/listener';
import { hideloading, showloading } from './global/loading.js';
import { luckysheetextendData } from './global/extend.js';
import { luckysheet_getcelldata } from './function/func';
import { transformExcelToLuckyJson, transformExcelToLuckyByBuffer } from './global/fromExcel';
import { exportExcel, exportExcelFromJson, exportExcelBlobFromJson } from './global/toExcel';
import { getMaxRowLen } from './global/getRowlen.js';
let luckysheet = {};

// mount api
// luckysheet.api = api;
// Object.assign(luckysheet, api);

luckysheet = common_extend(api, luckysheet);
luckysheet.created = false;
// 创建luckysheet表格
luckysheet.create = async function (setting) {
    method.destroy();
    // Store original parameters for api: toJson
    Store.toJsonOptions = {};
    for (let c in setting) {
        if (c !== 'data') {
            Store.toJsonOptions[c] = setting[c];
        }
    }

    let extendsetting = common_extend(defaultSetting, setting);

    let loadurl = extendsetting.loadUrl,
        menu = extendsetting.menu,
        title = extendsetting.title;

    let container = extendsetting.container;
    Store.container = container;
    Store.luckysheetfile = extendsetting.data;
    Store.defaultcolumnNum = extendsetting.column;
    Store.defaultrowNum = extendsetting.row;
    Store.defaultFontSize = extendsetting.defaultFontSize;
    Store.fullscreenmode = extendsetting.fullscreenmode;
    Store.lang = extendsetting.lang; // language
    Store.allowEdit = extendsetting.allowEdit;
    Store.limitSheetNameLength = extendsetting.limitSheetNameLength;
    Store.defaultSheetNameMaxLength = extendsetting.defaultSheetNameMaxLength;
    Store.fontList = extendsetting.fontList;
    // loading
    const loadingObj = luckysheetlodingHTML("#" + container);
    Store.loadingObj = loadingObj;
    server.gridKey = extendsetting.gridKey;
    server.loadUrl = extendsetting.loadUrl;
    server.updateUrl = extendsetting.updateUrl;
    server.updateImageUrl = extendsetting.updateImageUrl;
    server.title = extendsetting.title;
    server.loadSheetUrl = extendsetting.loadSheetUrl;
    server.allowUpdate = extendsetting.allowUpdate;
    Store.hideStatusBar = extendsetting.hideStatusBar;
    Store.hideTabBar = extendsetting.hideTabBar;
    Store.hideTitleBar = extendsetting.hideTitleBar;
    if (Store.hideTabBar) {
        extendsetting.showsheetbarConfig = {
            add: false,
            menu: false,
            sheet: false
        };
    }
    if (Store.hideStatusBar) {
        extendsetting.showstatisticBarConfig = {
            count: false,
            view: false,
            zoom: false
        };
    }
    luckysheetConfigsetting.autoFormatw = extendsetting.autoFormatw;
    luckysheetConfigsetting.accuracy = extendsetting.accuracy;
    luckysheetConfigsetting.total = extendsetting.data[0].total;
    luckysheetConfigsetting.loading = extendsetting.loading;
    luckysheetConfigsetting.allowCopy = extendsetting.allowCopy;
    luckysheetConfigsetting.showtoolbar = extendsetting.showtoolbar;
    luckysheetConfigsetting.showtoolbarConfig = extendsetting.showtoolbarConfig;
    luckysheetConfigsetting.showinfobar = extendsetting.showinfobar;
    luckysheetConfigsetting.showsheetbar = extendsetting.showsheetbar;
    luckysheetConfigsetting.showsheetbarConfig = extendsetting.showsheetbarConfig;
    luckysheetConfigsetting.showstatisticBar = extendsetting.showstatisticBar;
    luckysheetConfigsetting.showstatisticBarConfig = extendsetting.showstatisticBarConfig;
    luckysheetConfigsetting.sheetFormulaBar = extendsetting.sheetFormulaBar;
    luckysheetConfigsetting.cellRightClickConfig = extendsetting.cellRightClickConfig;
    luckysheetConfigsetting.sheetRightClickConfig = extendsetting.sheetRightClickConfig;
    luckysheetConfigsetting.pointEdit = extendsetting.pointEdit;
    luckysheetConfigsetting.pointEditUpdate = extendsetting.pointEditUpdate;
    luckysheetConfigsetting.pointEditZoom = extendsetting.pointEditZoom;
    luckysheetConfigsetting.userInfo = extendsetting.userInfo;
    luckysheetConfigsetting.userMenuItem = extendsetting.userMenuItem;
    luckysheetConfigsetting.myFolderUrl = extendsetting.myFolderUrl;
    luckysheetConfigsetting.functionButton = extendsetting.functionButton;

    luckysheetConfigsetting.showConfigWindowResize = extendsetting.showConfigWindowResize;
    luckysheetConfigsetting.enableAddRow = extendsetting.enableAddRow;
    luckysheetConfigsetting.enableAddBackTop = extendsetting.enableAddBackTop;
    luckysheetConfigsetting.addRowCount = extendsetting.addRowCount;
    luckysheetConfigsetting.enablePage = extendsetting.enablePage;
    luckysheetConfigsetting.pageInfo = extendsetting.pageInfo;

    luckysheetConfigsetting.editMode = extendsetting.editMode;
    luckysheetConfigsetting.beforeCreateDom = extendsetting.beforeCreateDom;
    luckysheetConfigsetting.workbookCreateBefore = extendsetting.workbookCreateBefore;
    luckysheetConfigsetting.workbookCreateAfter = extendsetting.workbookCreateAfter;
    luckysheetConfigsetting.remoteFunction = extendsetting.remoteFunction;

    luckysheetConfigsetting.fireMousedown = extendsetting.fireMousedown;
    luckysheetConfigsetting.forceCalculation = extendsetting.forceCalculation;
    luckysheetConfigsetting.plugins = extendsetting.plugins;
    luckysheetConfigsetting.autoGenerateOriginData = extendsetting.autoGenerateOriginData;
    luckysheetConfigsetting.rowHeaderWidth = extendsetting.rowHeaderWidth;
    luckysheetConfigsetting.columnHeaderHeight = extendsetting.columnHeaderHeight;

    luckysheetConfigsetting.defaultColWidth = extendsetting.defaultColWidth;
    luckysheetConfigsetting.defaultRowHeight = extendsetting.defaultRowHeight;

    luckysheetConfigsetting.title = extendsetting.title;
    luckysheetConfigsetting.container = extendsetting.container;
    luckysheetConfigsetting.hook = extendsetting.hook;

    luckysheetConfigsetting.pager = extendsetting.pager;

    luckysheetConfigsetting.initShowsheetbarConfig = false;

    luckysheetConfigsetting.imageUpdateMethodConfig = extendsetting.imageUpdateMethodConfig;
    luckysheetConfigsetting.pageSize = extendsetting.pageSize;
    luckysheetConfigsetting.protectDatakey = extendsetting.protectDatakey || luckysheetConfigsetting.protectDatakey;
    if (Store.lang === 'zh') flatpickr.localize(Mandarin.zh);
    // Store the currently used plugins for monitoring asynchronous loadingstaticSheetTransform
    Store.asyncLoad.push(...luckysheetConfigsetting.plugins);
    Store.isEdit = extendsetting.isEdit;
    // Register plugins
    initPlugins(extendsetting.plugins, extendsetting.data);

    // Store formula information, including internationalization
    functionlist();

    let devicePixelRatio = extendsetting.devicePixelRatio;
    if (devicePixelRatio == null) {
        devicePixelRatio = 1;
    }
    Store.devicePixelRatio = Math.ceil(devicePixelRatio);

    let sheetsData = extendsetting.sheetsData;
    sheetsData = sheetsData.map((sheet) => {
        const calcChain = [];
        const celldata = [];
        sheet.celldata.forEach((cell) => {
            if (cell && cell.v) {
                let vm = {};
                if (cell.v.v === '#d') {
                    vm.v = '#待查询';
                    vm.m = '';
                };
                if (cell.v.isInsert) delete cell.v.isInsert;
                const ns = nameStyleConvert(cell.v.ns);
                for (let key of Object.keys(ns)) {
                    cell.v[key] = ns[key];
                }
                for (let key of Object.keys(vm)) {
                    cell.v[key] = vm[key];
                }
            }
            celldata.push(cell);
            if (cell && cell.v && cell.v.f) {
                calcChain.push({
                    r: cell.r,
                    c: cell.c,
                    index: sheet.index
                });
            }
        });
        return {
            ...sheet,
            celldata,
            calcChain
        };
    });
    // 已经加载的行数
    Store.loadDataCount = {};
    sheetsData.forEach(s => {
        let maxRowLen = getMaxRowLen(s.celldata) || Store.defaultrowNum;
        Store.loadDataCount[s.index] = Store.defaultrowNum > maxRowLen ? maxRowLen : Store.defaultrowNum;
    });
    Store.luckysheetfile = sheetsData;
    sheetmanage.initialjfFile(menu, title);
    sheetsData.forEach((sheet, i) => {
        method.calContentCoordinate(sheet.index, [], sheet.celldata);
    });
    // luckysheetsizeauto();
    initialWorkBook();
    await initIcon();
    initDevtools();
    luckysheet.created = true;
};

// 初始化iconList, 创建 icon 对应的 img 标签
async function initIcon () {
    const iconList = Store.toJsonOptions.iconList || [];
    if (!iconList.length) return;
    let promiseList = [];
    for (let i = 0; i < iconList.length; i++) {
        let iconsPromise = new Promise((resolve, reject) => {
            const icon = Store.toJsonOptions.iconList[i];
            const dom = new Image();
            dom.src = icon.url;
            icon.dom = dom;
            dom.onload = resolve();
            dom.onerror = resolve();
        });
        promiseList.push(iconsPromise);
    }

    return Promise.all(promiseList);
}

async function initialWorkBook () {
    luckysheetHandler();// Overall dom initialization
    initialFilterHandler();// Filter initialization
    initialMatrixOperation();// Right click matrix initialization
    initialSheetBar();// bottom sheet bar initialization
    formulaBarInitial();// top formula bar initialization
    rowColumnOperationInitial();// row and coloumn operate initialization
    keyboardInitial();// Keyboard operate initialization
    orderByInitial();// menu bar orderby function initialization
    zoomInitial();// zoom method initialization
    printInitial();// print initialization
    initListener();
}

function updateluckysheetfile (config) {
    $.post(config.url, { "gridKey": server.gridKey, "offset": config.offset || 0, "rowCount": config.rowCount }, function (d) {
        // d.data.luckysheet_select_save = [{ row: [0, 100], column: [0, 20]}];
        // let data = new Function("return " + JSON.stringify([d.data]))();
        // Store.luckysheetfile = data;

        // setluckysheet_select_save([{ row: [0, 100], column: [0, 20]}])
        // api.refresh();
        for (let r = 0; r < config.rowCount; r++) {
            for (let c = 0; c < 20; c++) {
                const cd = d.data.celldata[r * 20 + c];
                setCellValue(r, c, cd.v);
            }
        }
    });
}

function initDevtools () {
    saveJSON();
}

function saveJSON () {
    let blob,
        a = document.createElement('a');
    a.download = `deep-data.js`;
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    a.onclick = function () {
        let stringifyData = JSON.stringify(Store.flowdata);
        blob = new Blob([`window.demoData = ${stringifyData}`], { type: 'text/json' });
        a.href = window.URL.createObjectURL(blob);
    };
    let infoDetailnDom = document.getElementById('luckysheet_info_detail_update');
    a.style = "font-size: 12px;";
    a.text = '下载sheet数据';
    infoDetailnDom.parentNode.appendChild(a);
}

// 获取所有表格数据
luckysheet.getluckysheetfile = getluckysheetfile;

luckysheet.updateluckysheetfile = updateluckysheetfile;

luckysheet.luckysheet_getcelldata = luckysheet_getcelldata;

// 获取当前表格 选区
luckysheet.getluckysheet_select_save = getluckysheet_select_save;

// 设置当前表格 选区
luckysheet.setluckysheet_select_save = setluckysheet_select_save;

// 获取当前表格 config配置
luckysheet.getconfig = getconfig;

// 二维数组数据 转化成 {r, c, v}格式 一维数组 (传入参数为二维数据data)
luckysheet.getGridData = sheetmanage.getGridData;

// 生成表格所需二维数组 （传入参数为表格数据对象file）
luckysheet.buildGridData = sheetmanage.buildGridData;

// Refresh the canvas display data according to scrollHeight and scrollWidth
luckysheet.luckysheetrefreshgrid = luckysheetrefreshgrid;

// Refresh canvas
luckysheet.jfrefreshgrid = jfrefreshgrid;

// Get the value of the cell
luckysheet.getcellvalue = getcellvalue;

// Set cell value
luckysheet.setcellvalue = setcellvalue;

// Get selection range value
luckysheet.getdatabyselection = getdatabyselection;

luckysheet.sheetmanage = sheetmanage;
// Data of the current table
luckysheet.flowdata = function () {
    return Store.flowdata;
};
luckysheet.Store = function () {
    return Store;
};

luckysheet.StoreAddattechmentTEST = function () {
    let temp = {
        "7_3": {
            "linkType": "external",
            "linkAddress": "https://www.baidu.com",
            "linkTooltip": ""
        },
        "7_1": {
            "linkType": "external",
            "linkAddress": "https://www.baidu.com",
            "linkTooltip": ""
        }
    };
    let rangebox = [];
    let currentHyperlinkObj = {};
    // loadAttechment.createDialog();
    for (let i in temp) {
        let arr = i.split('_');
        currentHyperlinkObj[i] = temp[i];
        rangebox.push({ row: [arr[0], arr[0]], column: [arr[1], arr[1]] });
    }
    hyperlinkCtrl.ref(
        {},
        currentHyperlinkObj,
        0,
        editor.deepCopyFlowData(Store.flowdata),
        rangebox
    );
};

luckysheet.StoreAddattechment = function () {
    let temp = {
        "10_9": {
            "linkAddress": {
                "fileName": "高小超.xlsx",
                "fileType": "ATT",
                "url": "/opt/file//file/spacewszoon/appwszoon012/ATT/2022/03/ATT2022031011402113683.xlsx",
                "id": "U_aa380cdd-1d57-4669-841c-603d2007c123"
            },
            "linkTooltip": ""
        }
    };
    let rangebox = [];
    let currentHyperlinkObj = {};
    // loadAttechment.createDialog();
    for (let i in temp) {
        let arr = i.split('_');
        currentHyperlinkObj[i] = temp[i];
        rangebox.push({ row: [arr[0], arr[0]], column: [arr[1], arr[1]] });
    }
    loadAttechment.ref(
        {},
        currentHyperlinkObj,
        0,
        editor.deepCopyFlowData(Store.flowdata),
        rangebox
    );
};

// Set selection highlight
luckysheet.selectHightlightShow = selectHightlightShow;

// Reset parameters after destroying the table
luckysheet.destroy = method.destroy;

luckysheet.showLoadingProgress = showloading;
luckysheet.hideLoadingProgress = hideloading;
luckysheet.luckysheetextendData = luckysheetextendData;
luckysheet.exportExcel = exportExcel;
luckysheet.exportExcelFromJson = exportExcelFromJson;
// luckysheet.exportExcelBlobFromJson = exportExcelBlobFromJson;
luckysheet.transformExcelToLuckyJson = transformExcelToLuckyJson;
luckysheet.transformExcelToLuckyByBuffer = transformExcelToLuckyByBuffer;

export {
    luckysheet
};
